<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/6/26 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------

namespace app\admin\controller;




use app\common\controller\AdminBaseController;
use app\common\model\tang\Cost as CostModel;
use app\common\model\tang\Feedback as FeedbackModel;
use app\common\model\tang\SubjectList;
use app\common\model\tang\CostRule;

class Report extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new CostRule();
    }

    public function index()
    {
//        $where = [];
//        $model = (new costRule())->select();
//
//
//        $where['pay_status'] = [1,-1];
//        $pay_type = SubjectList::where(['type' => 1, 'status' => 0])->field('id,name')->select()->toArray();
//        foreach ($pay_type as $key=>$value){
//            $where['subject_id'] = $value['id'];
//            $pay_type[$key]['child'] = $this->model->where($where)->with(['costType','merchants','costRule'])->select()->toArray();
//        }
//        $this->assign(compact("pay_type"));
//        return $this->fetch();

        if (IS_AJAX){
            $where = [
                'pid'         => 0,
                'pay_status'  => [1,-1],
            ] ;
            return $this->model->getAdminPageData($this->param, 'id desc',$where,static::$admin_info['nickname']);
        }
        $merchant_list =\app\common\model\tang\Merchant::field('id,merchant_sn,name,company,username,code')->select();
        //获取菜单列表
        $this->assign(compact("merchant_list"));
        return $this->fetch();
    }

    public function tongji(){
        if (IS_AJAX){
            $param = $this->param ;
            $CostModel = new CostModel();
            $where[]=['pay_status','=',1] ;
            $where[]=['pid','=',0] ;
            if(!empty($param['both_time'])){
                $time = explode(' - ',$param['both_time']);
                $where[]=['pay_time','>=',$time[0]] ;
                $where[]=['pay_time','<=',$time[1].' 23:59:59'] ;
            }
            $subjectall = $CostModel->where($where)->field('subject_id')->group('subject_id')->select()->toArray();
            if(!empty($subjectall)){  // 获取所有支付方式
                $paytype = [];
                foreach ($subjectall as $row1){
                    $paytype[] = $row1['subject_id'] ;
                }
                $allpay = SubjectList::where('id','in',$paytype)->field(['name','id'])->select()->toArray();
                if($allpay){
                    foreach ($allpay as $v){
                        $headers['pay'.$v['id']] = $v['name'];
                    }
                }
            }
            $data = [] ;
            $costall = $CostModel->where($where)->with(['costType','subjectList','payType'])->order('type')->select()->toArray();
            if($costall){
                $result=  [];
                // 获取所有值 根据项目名称分组
                foreach ($costall as $row){
                    switch ($row['type']){
                        case 1 :
                            $row['type'] = '押金' ;
                            break;
                        case 2 :
                            $row['type'] = '费用' ;
                            break;
                        case 3 :
                            $row['type'] = '证件' ;
                            break;
                    }
                    $rows = [
                        'amount'          => sprintf("%.2f",$row['amount']/100),
                        'cost_name'       => $row['costType']['cost_name'],
                        'department_id'   => $row['subjectList']['name'],
                        'subject_id'      => $row['subject_id'],  // 支付方式ID
                        'type'            => $row['type']
                    ];
                    $result[$rows['cost_name']][] = $rows ;
                }
                //  根据所属部门分组
                $result1=  [];
                foreach ($result as $key => $value){
                    foreach ($value as $value1){
                        $result1[$key]['name'] = $key;
                        $result1[$key]['data'][$value1['department_id']][] = $value1;
                    }
                }
                //  根据支付方式统计金额
                foreach ($result1 as &$item){
                    $childData = array_values($item['data']);
                    unset($item['data']);
                    foreach ($childData as $childItem){
                        $tempData = [];
                        foreach ($childItem as $childItem2){
                            foreach ($headers as  $headersKey => $headersItem){
                                $childItem2[$headersKey] = 0;
                            }
                            if(empty($tempData)){
                                $tempData = $childItem2;
                                $tempData['count'] = 0;
                            }
                            $tempData["pay".$childItem2['subject_id']] = empty($tempData["pay".$childItem2['subject_id']]) ? 0 : $tempData["pay".$childItem2['subject_id']];
                            $tempData["pay".$childItem2['subject_id']] += $childItem2['amount'];
                            $tempData["pay".$childItem2['subject_id']] =  sprintf("%.2f" ,$tempData["pay".$childItem2['subject_id']]);
                            $tempData['count'] += $childItem2['amount'];  //  每一行的合计
                        }
                        $tempData['count'] = sprintf("%.2f" ,$tempData['count']);
                        $data[] = $tempData;
                    }

                }
            }
            //  支付类型合计每一列
            $sum = [
                'type'            =>  '',
                'cost_name'       =>  '',
                'department_id'   => '合计',
            ];
            $headers['count'] = 0;
            foreach ($headers as  $headersKey => $headersItem){
                $childItem2[$headersKey] = 0;
                $sum[$headersKey] = empty($sum[$headersKey]) ? 0 : $sum[$headersKey];
                foreach ($data as $item){
                    foreach ($item as $childKey =>  $childItem){
                        if($childKey == $headersKey){
                            $sum[$headersKey] += $childItem;
                            $sum[$headersKey] = sprintf("%.2f" ,$sum[$headersKey]);
                        }
                    }
                }
            }
            $data[] = $sum;
            return parent::ajaxResult($data);
        }
        return $this->fetch();
    }

    public function TableHeaders(){
//        var_dump($this->request);die;
//        if (IS_AJAX){
            $param = $this->param ;
            $CostModel = new CostModel();
            $CostModel = $CostModel->where("pay_status",1)->where("pid",0);
            if(!empty($param['both_time'])){
                $time = explode(' - ',$param['both_time']);
                $CostModel = $CostModel->where("pay_time",">=",$time[0]);
                $CostModel = $CostModel->where("pay_time","<=",$time[1].' 23:59:59');
            }
            $headers = [
                'type'            =>  '类型',
                'cost_name'       =>  '项目名称',
                'department_id'   =>  '所属部门',
            ];
            $subjectall = $CostModel->field('subject_id')->group('subject_id')->select()->toArray();
            if(!empty($subjectall)){
                $paytype = [];
                foreach ($subjectall as $row){
                    $paytype[] = $row['subject_id'] ;
                }
                $allpay = SubjectList::where('id','in',$paytype)->field(['name','id'])->select()->toArray();
                if($allpay){
                    foreach ($allpay as $v){
                        $headers['pay'.$v['id']] = $v['name'];
                    }
                }
                $headers['count'] = '合计';
            }
            return $headers ;
//        }
    }

    public function export(){
        $where = [
            'pid'         => 0,
            'pay_status'  => [1,-1],
        ] ;
        $this->model->getAdminPageData($this->param, 'id desc',$where,static::$admin_info['nickname']);
    }


    // 转结存

    public function carryDown(){

         $list = $this->model->where(['is_carry_down'=>1,'carry_down_type'=>0])->select()->toArray();
         if(empty($list)){
             return parent::JsonReturn('没有结转的订单', 1);
         }
         foreach ($list as $v){
             $TaxMoneyArr = TaxMoney($v['z_money'],1,$v['tax_rate']);
             $TaxMoneyArr['carry_down_type'] = 1 ;
             $res = $this->model->update($TaxMoneyArr,['id'=>$v['id']]);
             if(!$res){
                 return parent::JsonReturn('结转失败', 1);
             }
         }
         return parent::JsonReturn('转结存成功', 0);
    }


    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:添加编辑
     */
    public function add()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            return $this->model->doAll($data);
        }
        $id = $this->request->param("id/d");//父id
        $info = $this->model->find($id);
        //获取菜单列表
        $this->assign(compact("info", "id"));
        return $this->fetch();
    }


}